package processor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.UsernamePasswordCredentials;
import pipeline.ZolPhonePipeline;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

/**
 * Created by zhangcheng on 2017/5/5 0005.
 */
@Slf4j
public class ZolPageProcessor implements PageProcessor {

    private Site site = Site.me()
            .setRetryTimes(10)
            .setHttpProxy(new HttpHost("10.101.1.6", 80))
            //.setUsernamePasswordCredentials(new UsernamePasswordCredentials("H9142YEPE0R727DD","B96781AC19AC1926"))
            .setSleepTime(1000);

    static final String LIST_PIREX = "http://detail.zol.com.cn/cell_phone_index/subcate57_0_list_1_0_1_2_0_\\w+\\.html";
    static final String DETAILS_PIREX = "http://detail.zol.com.cn/cell_phone/index\\w+\\.shtml";

    public void process(Page page) {
        if (page.getUrl().regex(LIST_PIREX).match()) {
            //page.addTargetRequests(page.getHtml().xpath("/html/body/div[5]/div[1]/div[5]/div[1]").links().all());
            page.addTargetRequests(page.getHtml().links().regex(DETAILS_PIREX).all());
        }else if(page.getUrl().regex(DETAILS_PIREX).match()){
            page.addTargetRequests(page.getHtml().xpath("//*[@id=\"tagNav\"]/ul/li[4]").links().all());
        } else {
            Html html = page.getHtml();
            String phone = html.xpath("//*[@id=\"page-title\"]/text()").get().replace("参数","");
            System.out.println("手机名称："+phone);
            page.putField("手机名称",phone);
            for(int i=1;i<100;i++){
                String name = html.xpath("//*[@id=\"newPmName_"+i+"\"]/tidyText()").get();
                String value = html.xpath("//*[@id=\"newPmVal_"+i+"\"]/tidyText()").get();
                if(StringUtils.isNotBlank(name)){
                    value = value.replaceAll("[<](.*?)[>]", "").replace("\n","");
                    page.putField(name,value);
                }else{
                    break;
                }
            }
        }
    }

    public Site getSite() {
        return site;
    }

    static int threadNum = 1;
    public static void main(String[] args) throws Exception{


        Spider spider = Spider.create(new ZolPageProcessor())
                .addPipeline(new ZolPhonePipeline("G:\\data"))
                .thread(threadNum);
        //spider.addUrl("http://detail.zol.com.cn/cell_phone/index349997.shtml");
        String LIST_PIREX = "http://detail.zol.com.cn/cell_phone_index/subcate57_0_list_1_0_1_2_0_%d.html";
        for(int i=2;i<104;i++){
            spider.addUrl(String.format(LIST_PIREX,i));
        }
        spider.run();

    }
}
